package com.example.registration.service;

import com.example.registration.entity.Registration;
import com.example.registration.entity.RegistrationLimit;
import com.example.registration.mapper.RegistrationMapper;
import com.example.registration.mapper.RegistrationLimitMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegistrationService {
    
    private static final String PHONE_COOKIE_NAME = "user_phone";
    
    @Autowired
    private RegistrationMapper registrationMapper;
    
    @Autowired
    private RegistrationLimitMapper registrationLimitMapper;

    /**
     * 保存报名信息
     * @param registration 报名实体
     * @return 处理结果
     */
    public Map<String, Object> saveRegistration(Registration registration) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取最新的报名限制条件
        RegistrationLimit limit = registrationLimitMapper.getLatestLimit();
        
        // 如果没有设置限制，允许报名
        if (limit == null) {
            boolean saved = registrationMapper.insert(registration) > 0;
            result.put("success", saved);
            result.put("message", saved ? "报名信息提交成功！" : "报名信息提交失败，请稍后重试。");
            return result;
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        // 检查当前时间是否在报名时间范围内
        if (now.isBefore(limit.getStartTime()) || now.isAfter(limit.getEndTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String timeRange = limit.getStartTime().format(formatter) + " ~ " + limit.getEndTime().format(formatter);
            
            result.put("success", false);
            result.put("message", "报名时间为：" + timeRange);
            return result;
        }
        
        // 检查报名人数是否已满 - 从registrationMapper中获取报名人数
        int currentCount = registrationMapper.getRegistrationCountByLimitId(limit.getId());
        if (currentCount >= limit.getMaxCount()) {
            result.put("success", false);
            result.put("message", "报名名额已满");
            return result;
        }
        
        // 设置报名限制ID
        registration.setRegistrationLimitId(limit.getId());
        
        // 检查手机号是否已报名
        int existCount = registrationMapper.countByLimitIdAndPhone(limit.getId(), registration.getContactPhone());
        if (existCount > 0) {
            result.put("success", false);
            result.put("message", "该手机号已报名，请勿重复提交");
            return result;
        }
        
        // 保存报名信息
        boolean saved;
        try {
            saved = registrationMapper.insert(registration) > 0;
            result.put("success", saved);
            result.put("message", saved ? "报名信息提交成功！" : "报名信息提交失败，请稍后重试。");
            
            // 如果保存成功，将ID置入结果中
            if (saved) {
                result.put("registrationId", registration.getId());
            }
        } catch (Exception e) {
            // 捕获可能的唯一键冲突异常
            result.put("success", false);
            result.put("message", "该手机号已报名，请勿重复提交");
        }
        
        return result;
    }
    
    /**
     * 根据请求中的Cookie获取用户最近的报名信息
     * @param request HTTP请求
     * @return 报名信息实体
     */
    public Registration getLastRegistrationByContactPhone(HttpServletRequest request) {
        // 从Cookie中获取用户手机号
        String phoneNumber = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (PHONE_COOKIE_NAME.equals(cookie.getName())) {
                    phoneNumber = cookie.getValue();
                    break;
                }
            }
        }
        
        // 如果没有找到手机号，返回null
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return null;
        }
        
        // 根据手机号查询最新的报名信息
        return registrationMapper.findLastByContactPhone(phoneNumber);
    }

    /**
     * 根据联系电话获取报名信息
     * @param contactPhone 联系电话
     * @return 报名信息实体
     */
    public Registration getRegistrationByContactPhone(String contactPhone) {
        if (contactPhone == null || contactPhone.isEmpty()) {
            return null;
        }
        
        return registrationMapper.findLastByContactPhone(contactPhone);
    }
    
    /**
     * 获取所有报名信息
     * @return 报名信息列表
     */
    public List<Registration> getAllRegistrations() {
        return registrationMapper.findAll();
    }
    
    /**
     * 根据ID获取报名信息
     * @param id 报名ID
     * @return 报名信息
     */
    public Registration getRegistrationById(Long id) {
        return registrationMapper.findById(id);
    }
    
    /**
     * 更新报名状态
     * @param id 报名ID
     * @param status 状态
     * @return 是否更新成功
     */
    public boolean updateRegistrationStatus(Long id, String status) {
        return registrationMapper.updateStatus(id, status) > 0;
    }
    
    /**
     * 删除报名信息
     * @param id 报名ID
     * @return 是否删除成功
     */
    public boolean deleteRegistration(Long id) {
        return registrationMapper.deleteById(id) > 0;
    }
}